package org.icress.fusion.ws

/*
import org.hibernate.FetchMode as FM
import grails.converters.JSON
import org.hibernate.criterion.CriteriaSpecification

import org.icress.fusion.wf.WorkflowHistory
import org.icress.fusion.wf.WorkflowAction
import org.icress.fusion.wf.WorkflowStep

import org.icress.fusion.b2b.SalesOrder

import org.icress.fusion.shiro.User

import org.icress.fusion.admin.Group
*/
class TestInboundController {

    //def fmapResult = [:]

    def inboundSalesOrderService

    def index = { 

        //init params
        def salesOrderId = '1' 
        def action = 'Y'

        def result = inboundSalesOrderService.approval(salesOrderId, action)
        
/*
        def stauts = checkWorkFlowStep(salesOrderId, action)

        if(stauts == true){
            fmapResult.put('0', '审批成功')
        }

        render """
            stauts=${stauts}
            <br>
            fmapResult=${fmapResult}
        """
*/
        render "result=${result}"
    }
/*
    def checkWorkFlowStep(salesOrderId, action) {
        def workflowHistory = getCurrentHistory(salesOrderId, action)

        if(workflowHistory == null){
            fmapResult.put('-1', '未找到审批历史')
            return false;
        }

        def historyId = workflowHistory[0]//workflow history's id
        def actionId = workflowHistory[1]//workflow belongsTo step's action's id
        def version = workflowHistory[2]//workflow history's version
        def objectName = 'salesOrder'
        def objectId = salesOrderId
        def description = 'approval form erp'


		if(!checkAssignee(actionId)){
            fmapResult.put('-2', '您不是当前的任务分配人')
			return false
		}
        
		if(!checkHistory(historyId, version)){
            fmapResult.put('-3', '另外一个用户更新了审批历史，请重试')
			return false
		}
        
		def nextStep = getNextStep(actionId)
		if(nextStep != null){
			if(createNextStep(nextStep, objectName, objectId)){
				return finishCurrentStep(historyId, description)
			}
		}else{
			return finishCurrentStep(historyId, description)
		}
        
    }
    

    //取待审批商务部的workflow history
    def getCurrentHistory(salesOrderId, action){
		return WorkflowHistory.withCriteria(uniqueResult:true){

            createAlias 'step', 'step', CriteriaSpecification.LEFT_JOIN
            createAlias 'step.actions', 'action', CriteriaSpecification.LEFT_JOIN
            projections{
                property("id", "historyId")
                property("action.id", "actionId")
                property("version", "version")
            }
            
            fetchMode "step", FM.JOIN
            fetchMode "step.actions", FM.JOIN

			eq("objectName", 'salesOrder')
			eq("objectId", salesOrderId)
            eq("status", '进行中')
            eq("step.name", '待审批（商务部）')
            eq("action.name", (action == 'Y')?'通过':'拒绝')
		}
	}

    //取订单
    def getSalesOrder(salesOrderId){
        return SalesOrder.withCriteria(uniqueResult:true){
            projections{
                property("owner.id", "ownerId")
            }
			eq("id", salesOrderId)
		}
    }

    //检查分配人,如果分配人为空，则判断是否是当前用户，否则判断当前用户是否在分配的组中
	def checkAssignee(actionId){
		def result = false
        //get user, default commercial
        def currentUser = User.findByUsername("3002_1")
		//get action belongsto step's id
		def currentStepId = WorkflowAction.get(actionId).belognsToStep?.id
        //get step assignee's id
		def assigneeId = WorkflowStep.get(currentStepId)?.assignee?.id
        //判断用户是否在分配的组中
		if(assigneeId != null){
			Group.get(assigneeId).users.each{
				if(it.id == currentUser.id) {
					result = true
				}
			}
		}
		return result
	}

	//检查历史是否已完成或者版本不一致
	def checkHistory(historyId, version){
		def result = true
		def history = WorkflowHistory.get(historyId)
		
		if(history.version != version.toLong() || history.status == '已完成'){
			result = false
		}
		return result
	}

    //获取下一步
	def getNextStep(actionId){
		def nextStepId = WorkflowAction.get(actionId)?.nextStep?.id
		def nextStep = null
		if(nextStepId != null){
			nextStep = WorkflowStep.get(nextStepId)
		}
		return nextStep
	}
	//创建下一步
	def createNextStep(nextStep, objectName, objectId){
        //get user
        def currentUser = User.findByUsername("3002_1")
        def history = new WorkflowHistory(
			  step : nextStep
			, objectName : objectName
			, objectId : objectId
			, status : (nextStep.isEnd)?'已完成':'进行中'
			, description : ''
			, createdBy : currentUser
			, lastModifiedBy : currentUser
			, dateCreated : new Date()
			, lastUpdated : new Date()
		).save(flush:true)
        log.info("history=${history.ident()}")
        def result = (history.ident())?true:false
		if(result == false){
            fmapResult.put('-5', '创建审批历史失败')
        }
		return result
	}
	//标记当前history为已完成
	def finishCurrentStep(historyId, description){
        def result = false

		def history = WorkflowHistory.get(historyId)
            history.status = '已完成'
            history.description = description
	        
        result = history.validate() && history.save(flush:true)
        if(result == false){
            fmapResult.put('-6', '结束当前审批历史失败')
        }
        return result
	}  
*/
}
